const fs = require('fs');
const path = require('path');
const moment = require('moment');

// 设置日志文件的目录和文件名格式  
const logDir = './logs';
const logFileName = 'api-log-';
const logFileExtension = '.log';

// 创建日志目录（如果不存在）  
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

// 获取当前日期并格式化为YYYY-MM-DD格式   
const currentDate = moment().format('YYYY-MM-DD');

// 构建日志文件名  
const logFilePath = path.join(logDir, `${logFileName}${currentDate}${logFileExtension}`);

// 创建日志文件并设置追加模式（不会覆盖现有内容）  
const logFileStream = fs.createWriteStream(logFilePath, { flags: 'a' });

const info = (req) => {
  logFileStream.write(`${new Date().toISOString()} - INFO - ${req.method} - ${req.url} - ${req.rawHeaders} \n`)
}

const error = (err,req) => {
  logFileStream.write(`${new Date().toISOString()} - ERROR - ${req.method} - ${req.url} - ${req.rawHeaders} \n`)
  if(err){
    logFileStream.write(`${new Date().toISOString()} - ERROR - ${err} \n`)
  }
}

module.exports = { info, error }